<template>
  <div class="container">
    <!-- 要转换的目标区域 -->
    <div ref="captureRef" class="content-box">
      <h1>要转换的内容</h1>
      <p>当前时间：{{ new Date().toLocaleString() }}</p>
      <div class="styled-box">样式测试</div>
    </div>

    <button @click="capture">生成截图</button>

    <!-- 预览区域 -->
    <div v-if="imageUrl" class="preview">
      <img :src="imageUrl" alt="生成的图片">
      <a :href="imageUrl" download="screenshot.png">下载图片</a>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import html2canvas from 'html2canvas';

const captureRef = ref(null);
const imageUrl = ref('');

const capture = async () => {
  if (!captureRef.value) return;

  try {
    const canvas = await html2canvas(captureRef.value, {
      useCORS: true, // 允许跨域图片
      scale: 2,     // 提高分辨率
      logging: true, // 开启日志调试
      backgroundColor: '#ffffff'
    });

    imageUrl.value = canvas.toDataURL('image/png');
  } catch (error) {
    console.error('截图失败:', error);
  }
};
</script>

<style>
.content-box {
  padding: 20px;
  border: 1px solid #ccc;
  background: white;
}

.styled-box {
  width: 200px;
  height: 100px;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.preview {
  margin-top: 20px;
  padding: 10px;
  border: 1px dashed #666;
}

.preview img {
  max-width: 100%;
  border: 1px solid #ddd;
}
</style>
